package com.btkjgc.controller;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.extend.DictionaryModel;
import com.btkjgc.models.extend.PropertyUniqueModel;
import com.btkjgc.utils.HibernateUtil;

@Controller
public class CommonController extends BaseController {
 
	/**
	 * 参数 category,isquery
	 */
	@RequestMapping("/selectByComboCategory")
	@ResponseBody
	public List selectByComboCategory(DictionaryModel dictionaryModel) {

		List<Dictionary> list = null;
		String sql=	null;
		try {

		 
		    sql=	" select distinct d.type  from dictionary_t d where name ='"
							+ dictionaryModel.getName() + "'";
		    
			int type = HibernateUtil.executeSQLQueryInt(sql);
			
			String parentidStr=StringUtils.isEmpty(dictionaryModel.getParentidStr())? null:dictionaryModel.getParentidStr();
			
			
			//单选框
			if(!dictionaryModel.getMultiple()){
				
				if (type ==2) {

					// 查询字典数据字典配置的sql
					sql="select d.sql from dictionary_t d where name ='"
							+ dictionaryModel.getName() + "'";
					
					sql   = (String) HibernateUtil.executeSQLQueryObject(sql);
					
					if("City".equals(dictionaryModel.getName())){
						
						
						sql =sql.replace("${where}"," ParentId =("+parentidStr+")");
					}
					if("Area".equals(dictionaryModel.getName())){
						
						sql =sql.replace("${where}"," ParentId =("+parentidStr+")");
					}
					if("Role".equals(dictionaryModel.getName())){
						sql=sql.replace("${where}","and Level <="+ getLoginUser().getRoleLevel());
					}
					list =  HibernateUtil.executeSQLQueryList(sql, DictionaryModel.class);

				} else if (type == 0) {

					// 查询字典数据字典配置的是常量
					 sql="select d.name as value,d.key from dictionary_t d where name ='" + dictionaryModel.getName() + "'";
				     list =   HibernateUtil.executeSQLQueryList(sql,Dictionary.class);

				}
			}else {
				
				//多选框
				if (type ==2) {
					
					sql="select d.sql from dictionary_t d where name ='"
							+ dictionaryModel.getName() + "'";
					
					sql   = (String) HibernateUtil.executeSQLQueryObject(sql);
					
				    List resultlist=new ArrayList<>();
			 
					if("City".equals(dictionaryModel.getName())){
					 
						resultlist.addAll(getMultipleList(parentidStr,sql));
						
					}else if("Area".equals(dictionaryModel.getName())){
						
						resultlist.addAll(getMultipleList(parentidStr,sql));
					}else if("Province".equals(dictionaryModel.getName())){
						list =  HibernateUtil.executeSQLQueryList(sql, DictionaryModel.class);
						DictionaryModel dictionaryModel2=new DictionaryModel();
						dictionaryModel2.setValue("省份");
						list.add(0, dictionaryModel2);
						resultlist.add(list);
					}else{
						list =  HibernateUtil.executeSQLQueryList(sql, DictionaryModel.class);
						DictionaryModel dictionaryModel2=new DictionaryModel();
						dictionaryModel2.setValue("");
						list.add(0, dictionaryModel2);
						resultlist.add(list);
					}
					
					
					return resultlist;
		
				} 
			}


		} catch (Exception ex) {

			ex.printStackTrace();
			logger.error("出错:", ex);
		}
 
		return list;

	}
	
	
	public List getMultipleList(String ids,String sql) {
		
		List list = new ArrayList<>();

		if(!StringUtils.isEmpty(ids)){
			
		    String idarr[] = ids.split(",");
		    for (int i = 0; i < idarr.length; i++) {
		    	List sonList=new ArrayList<>();
		    	DictionaryModel parentDictionaryModel=(DictionaryModel) HibernateUtil.executeSQLQueryObject(sql.replace("${where}","  id=("+idarr[i]+")"), DictionaryModel.class);
		    	sonList.add(parentDictionaryModel);
		    	
		    	String sqlTemp =sql.replace("${where}"," parentId =("+idarr[i]+")");
		    	List templist=HibernateUtil.executeSQLQueryList(sqlTemp, DictionaryModel.class);
		    	sonList.addAll(templist);
		    	list.add(sonList);
		    }
		}
	 
		

	    
		return list;
	}
	
	/**
	 * 根据传入的属性名和值判断是否和已有的数据重复
	 * @param uniqueObj
	 * @return
	 */
	@RequestMapping("/checkNameUnique")
	@ResponseBody
	public Boolean checkNameUnique(HttpServletRequest request,PropertyUniqueModel propertyUniqueModel) {
		
		  AjaxObj ajaxObj=new AjaxObj();
		  ajaxObj.setResult(true);
		
		
		  Map map = new HashMap(); 
		  Enumeration paramNames = request.getParameterNames(); 
		  
		  //考虑到jquery.validate 的remote无法传递propertyvalue参数的情况
	      while (paramNames.hasMoreElements()) {
		  String paramName = (String) paramNames.nextElement();

				String[] paramValues = request.getParameterValues(paramName);
				if (paramValues.length == 1) {
					String paramValue = paramValues[0];
					if (paramValue.length() != 0) {
						System.out.println("参数：" + paramName + "=" + paramValue);
						map.put(paramName, paramValue);
						if(StringUtils.isEmpty(propertyUniqueModel.getPropertyvalue())
								&&!"category".equals(paramName)&&!"where".equals(paramName)){
							propertyUniqueModel.setPropertyvalue(paramValue);
						}
					}
				}
			}
 
		PropertyUniqueModel propertyUniqueModel2 =	 (PropertyUniqueModel) HibernateUtil.executeSQLQueryObject("select * from property_unique_t where category='"+propertyUniqueModel.getCategory()+"'",PropertyUniqueModel.class);
		propertyUniqueModel2.setPropertyvalue(propertyUniqueModel.getPropertyvalue());
		propertyUniqueModel2.setId(propertyUniqueModel.getId());
		
		 
		String sql=" select count(*) " +
				   " from "+propertyUniqueModel2.getTablename()+
				   " where "+propertyUniqueModel2.getPropertyname()+" ='"+propertyUniqueModel2.getPropertyvalue()+"'";
		
		if(!StringUtils.isEmpty(propertyUniqueModel.getId())){
			sql=sql+" and "+propertyUniqueModel2.getIdname()+"!="+propertyUniqueModel2.getId();
		}
		if(!StringUtils.isEmpty(propertyUniqueModel.getWhere())){
			sql=sql+"  "+propertyUniqueModel.getWhere();
		}
		
		logger.info(sql);
		int count= HibernateUtil.executeSQLQueryInt(sql);
		if(count>0){
			ajaxObj.setResult(false);
		}
		
		return ajaxObj.isResult();
	}
	


}
